<template>
   <div class="dark bd-content h-full" >
       <div class="time_area text-red-700 text-sm bg-gray-300">&nbsp;当前时间 : {{currentTime}}</div>
       <div class="bd-table  " :style="{ height: bgTableHeight + 'px' }">
         <el-table  size="small" :data="bdList"  border  class=" dark:bg-black text-white  "  @selection-change="handleSelectionChange" >
        
            <el-table-column  prop="id"  label="ID"  width="60" align="center"></el-table-column>
            <el-table-column  prop="web_name"   label="网站名称"  width="80" show-overflow-tooltip  align="center"></el-table-column>
            <el-table-column  prop="seourl"   label="URL"  width="120" show-overflow-tooltip  align="center"></el-table-column>
            <el-table-column  prop="seokeyword"   label="关键词"  width="" show-overflow-tooltip  align="center"></el-table-column>

            <el-table-column  prop="isuse"  label="使用否"  width="80"  align="center">
              <template #default="scope">
                <span v-if="scope.row.ISUSE==1">正常</span>
                <span v-if="scope.row.ISUSE==0">停用</span>
              </template>
            </el-table-column>

            <el-table-column  prop="clicktotal"  label="轮次"  width="60"  align="center">
                <template #default="scope">
                  <span v-if="scope.row.clicktotal==0"></span>
                </template>
            </el-table-column>
            <el-table-column  prop="successtotal"  label="成功次数"  width="70"  align="center">
                <template #default="scope">
                  <span v-if="scope.row.successtotal==0"></span>
                </template>
            </el-table-column>
            <el-table-column  prop="lasttime_fmt"  label="最后时间"  width="140"  align="center"></el-table-column>
            <el-table-column  prop="remark"   label="备注"  width="80" show-overflow-tooltip  align="center"></el-table-column>
            <el-table-column fixed="right" label="操作" width="130" align="center">
              <template #default="scope">
                <span v-if="scope.row.isuse==1">
                    <el-button link type="danger" class="mr-2" size="small" @click="statusChange(scope.row)">停止</el-button>
                </span>
                <span v-if="scope.row.isuse==0">
                    <el-button link size="small" class="mr-2" @click="statusChange(scope.row)">启动</el-button>
                </span>
  <!--              <el-button link type="primary" size="small" @click="jEdit(scope.row)">修改</el-button>-->
                <el-button link type="warning" size="small" @click="jDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
         </el-table>
       </div>
       <div class="bglogs "  >
          <Bdlog ref="bdlogRef"  />
       </div>

       <div class="footer-button"  >
         <el-row class="pt-2 flex items-center" >
<!--               <el-select v-model="btnOption" clearable placeholder="批量操作" size="small" class="w-24 ml-2" @click="batchChange">-->
<!--                  <el-option-->
<!--                    v-for="item in btnOptions"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                  />-->
<!--                </el-select>-->

                <el-select v-model="loop_option" class="m-2 w-20" placeholder="不限循环次数" size="small">
                  <el-option
                    v-for="item in loop_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>

               <el-button  size="small"  round class="bg-black text-white ml-8 mr-2 " style="padding:1rem" @click="bdStart" v-if="bdstart_status==0"><i class="fa fa-play" aria-hidden="true"></i>&nbsp;启 动</el-button>

               <el-button  size="small" round class="bg-green-500 text-white ml-8 mr-2 ml-8 mr-2 " style="padding:1rem" @click="bdStop" v-if="bdstart_status==1"><i class="fa fa-stop" aria-hidden="true"></i>>&nbsp;停 止</el-button>

               <el-button  size="small" round class="bg-blue-700 text-white ml-8 mr-2 " style="padding:1rem" @click="openAdd" ><i class="fa fa-pencil-square-o" aria-hidden="true"></i>&nbsp;添&nbsp;&nbsp;加</el-button>

               <el-button  size="small" round class="bg-blue-700 text-white ml-8 mr-2 " style="padding:1rem" @click="clearBlogs" ><i class="fa fa-times" aria-hidden="true"></i>&nbsp;清空日志</el-button>

               <el-button  size="small" round class="bg-blue-700 text-white ml-8 mr-2 " style="padding:1rem"  @click="setconf_drawer = true"   ><i class="fa fa-bars" aria-hidden="true"></i>&nbsp;配置</el-button>

<!--                <el-button  size="small" round class="bg-green-500 text-white ml-8 mr-2 ml-8 mr-2 " style="padding:1rem" @click="dialogTxtFormVisible=true" ><i class="fa fa-times" aria-hidden="true"></i>&nbsp;批量添加</el-button>-->
<!--                <el-button  size="small" round class="bg-blue-700 text-white ml-8 mr-2 " style="padding:1rem" @click="statusChangeAll" > <i class="fa fa-hand-paper-o" aria-hidden="true"></i> &nbsp;批量停用</el-button>-->
<!--                <el-button  size="small" round class="bg-green-500 text-white ml-8 mr-2 " style="padding:1rem" @click="batch_del">-->
<!--                  <i class="fa fa-bomb" aria-hidden="true"></i>&nbsp;批量删除</el-button>-->
<!--                <el-button  size="small" round class="bg-blue-700 text-white " style="padding:1rem" @click="clearAll" ><i class="fa fa-bomb" aria-hidden="true"></i> &nbsp;清空数据</el-button>-->
         </el-row>
       </div>

    </div>

        <el-dialog v-model="dialogFormVisible" :title="dialogFormTitle">
          <el-form ref="ruleFormRef"  :model="ruleForm"  status-icon
              :rules="rules"  label-width="120px"  class="demo-ruleForm" >
              <el-form-item label="网站名称" prop="web_name" size="small">
                <el-input v-model="ruleForm.web_name" autocomplete="off"  />
              </el-form-item>

              <el-form-item label="链接" prop="seourl" size="small">
                <el-input v-model="ruleForm.seourl" type="input" autocomplete="off" />
              </el-form-item>

              <el-form-item label="关键词" prop="seokeyword" size="small">
                <el-input v-model="ruleForm.seokeyword" autocomplete="off"  />
              </el-form-item>

              <el-form-item label="备注" prop="remark" size="small">
                <el-input type="textarea" v-model="ruleForm.remark" autocomplete="off"  />
              </el-form-item>

              <el-form-item label="选择状态" prop="isuse" size="small">
                <el-radio-group v-model="ruleForm.isuse">
                  <el-radio label="1" border>正常</el-radio>
                  <el-radio label="0" border>停止</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item>
                <el-button  class="bg-blue-500 text-white ml-[60%]"  @click="submitForm()" size="small">提交</el-button>
                <el-button @click="resetForm(ruleFormRef)" size="small">重置</el-button>
              </el-form-item>

              <el-input type="hidden" v-model="ruleForm.id" />
          </el-form>
        </el-dialog>

        <el-dialog v-model="dialogTxtFormVisible" title="批量输入内容">
          <el-form
              ref="ruleTxtFormRef"
              :model="ruleTxtForm"
              status-icon
              :rules="rulesTxt"
              label-width="70px"
              class="demo-ruleForm"
            >
              <el-form-item label="粘贴内容" prop="txtlines" size="small">
                <el-input type="textarea" v-model="ruleTxtForm.txtlines" autocomplete="off" placeholder="网站名称||网站链接||关键词" :rows="13"  />
              </el-form-item>
              <el-form-item>
                <el-button  class="bg-blue-500 text-white ml-[60%]"  @click="submitTxtForm()" size="small">提交</el-button>
                <el-button @click="resetTxtForm(ruleTxtFormRef)" size="small">重置</el-button>
              </el-form-item>
          </el-form>
        </el-dialog>

        <el-drawer class="setconf_wrap dark:bg-black  " v-model="setconf_drawer"  direction="rtl" >
           <Setconf/>
        </el-drawer>
  
</template>


<script setup>
import { ref, onMounted,getCurrentInstance,watch } from 'vue';
import { ElMessage ,ElMessageBox ,ElDrawer } from 'element-plus'
import Bdlog from './Bdlog.vue'
import Setconf from './Setconf.vue'
import { useBdStore } from '@/stores/bdStore.js';

import axios from 'axios'
import Mock from "mockjs";
let bdList = ref([])
const Random = Mock.Random;
const useStore = useBdStore()
const dialogFormVisible = ref(false)
const dialogTxtFormVisible = ref(false)
const dialogFormTitle = ref('新增')
const modify_status = ref(1) 
const ruleFormRef = ref(null)
const ruleTxtFormRef = ref(null)
const currentTime = ref(null)
const bdstart_status = ref(0)
const bdlogRef = ref()
const setconf_drawer = ref(false)
const direction = ref('rtl')
const btnOptions = [
   {value: 'batch_add', label: '批量添加'},
   // {value: 'batch_status_stop', label: '批量停用'},
   // {value: 'batch_del', label: '批量删除'},
]
const btnOption =ref(null)
const bgTableHeight = ref(0)
const dialogDisclaimerVisible  = ref(false)
const disclaimer_Txt = ref("")

const disclaimer_agree = ref(false)

const loop_options = [
   {value: -1, label: '不限次数'},
   {value: 2, label: '循环2次'},
   {value: 10, label: '循环10次'},
   {value: 20, label: '循环20次'},
   {value: 30, label: '循环30次'},
   {value: 40, label: '循环40次'},
   {value: 50, label: '循环50次'},
   {value: 100, label: '循环100次'}
]

const loop_option = ref(-1)
 
const ruleForm = ref({
  id:0,
  web_name:"",
  seourl:"",
  seokeyword:"",
  getstatus:1,
  remark:''
})

const rules = ref({
  seourl:[
    {required:true, message:'不能为空',trigger:'blur'}
  ],
  web_name:[
    {required:true, message:'不能为空',trigger:'blur'}
  ],
  seokeyword:[
    {required:true, message:'不能为空',trigger:'blur'}
  ],
  getstatus:[
    {required:true, message:'不能为空',trigger:'blur'}
  ]
})

const ruleTxtForm = ref({
  txtlines:""
})

const rulesTxt = ref({
  txtlines: [
    {required: true, message: '不能为空', trigger: 'blur'}
  ]
})

const appcd = ref('')
const appcdkey = ref('')

const appfirstTime = ref(0)
const firstTimeVisible = ref(false)

onMounted(()=>{
    setTimeout(()=>{       
       bdGetconfCache();
    },300)
})



const bdGetconfCache = (() => {
    window.pywebview.api.pybdSetconfCache().then((r) => {
      if (r==null || r == false) {
          appcdkey.value = '';
      } else {
          appcdkey.value = r.appcdkey
          appfirstTime.value = r.appfirstTime?r.appfirstTime:0
          init()         
      }
    })

})

 
const init = (()=>{
   window.addEventListener('resize', bdResize);
   bdGetList();
})

const bdGetList = (() => {
    jMaterial_getList()
    setInterval(() => {
       jMaterial_getList()
       bdResize()
    },3000)
    getCurrentTime()
})


// 监控 disclaimer_agree 的变化
// watch(() => disclaimer_agree.value, (newValue, oldValue) => {
//     // debugger
//     // bdResize()
// });


const bdResize = () => {
      if (document.getElementsByClassName('bglogs').length>0) {
        const windowHeight = window.innerHeight;
        // 确保两个div的高度之和不超过浏览器窗口的最大高度
        let bglogsHeight = document.getElementsByClassName('bglogs')[0].offsetHeight
        let footerHeight = document.getElementsByClassName('footer-button')[0].offsetHeight
        let logoHeight = document.getElementsByClassName('logo')[0].offsetHeight
        bgTableHeight.value = windowHeight - bglogsHeight - footerHeight - logoHeight - 60;
        // document.location.reload()
      }
}



const jEdit = ((row)=>{
    modify_status.value=1
    dialogFormVisible.value = true
    dialogFormTitle.value = "修改"
    ruleForm.value.id=row.id;
    ruleForm.value.seourl=row.seourl;
    ruleForm.value.web_name=row.web_name;
    ruleForm.value.seokeyword=row.seokeyword;
    ruleForm.value.isuse=row.isuse+ '';
    ruleForm.value.remark=row.remark;
})


const jDelete = ((id)=>{
  ElMessageBox.confirm('确定操作吗?')
     .then(() => {
        for (const i in bdList.value) {
            if (id == bdList.value[i].id) {
                window.pywebview.api.pymaterial_deleteRec(bdList.value[i]).then((r) => {
                    if (r.status=='success') {
                        bdList.value.splice(i,1)
                        return ElMessage({
                            message: '数据配置保存成功',
                            type: 'success',
                          })
                    } else {
                        return ElMessage({
                            message:r.message ,
                            type:'warning',
                          })
                    }
                })
            }
        }
     })
     .catch(() => {
      // catch error
     })


})


const openAdd = (()=>{
    modify_status.value=0;
    dialogFormVisible.value=true;
    dialogFormTitle.value = "新增"
    ruleForm.value.id=0;
    ruleForm.value.seourl='';
    ruleForm.value.web_name='';
    ruleForm.value.seokeyword='';
    ruleForm.value.isuse="1";
    ruleForm.value.remark='';
})

const statusChange = ((row)=>{
  let id = row.id
  let val = row.isuse==1?0:1
  for (const i in bdList.value) {
    if (id == bdList.value[i].id) {
      bdList.value[i].isuse = val  
      window.pywebview.api.pyUpdateIsuerRec(row).then(r=>{   })
    }
  }
})

// 重置的操作;
const resetForm = (val) => {
  if (!val) return
  val.resetFields()  // resetFields 函数：是将表单字段的值重置为其默认值;
}

const submitForm = (()=>{
    if (!ruleForm.value) return
      ruleFormRef.value.validate((valid) => {  // 注意：此时使用的是 ruleFormRef.value，而仅写 ruleFormRef 是拿不到值且会报错的;
        if (valid) { 
          if (modify_status.value==1) {
             doModify(ruleForm.value)
          } else {            
            window.pywebview.api.pyAddRec(ruleForm.value).then(r=>{  
              let mtype = 'success'
              if (r.status=='fail') {
                 mtype='warning'
              } else {
                bdList = ref([])
                jMaterial_getList()
              }
              return ElMessage({
                    message: r.message,
                    type:mtype,
                  }) 
            })
          }
          console.log('submit!')
        } else {
          console.log('error submit!')
          return false
        }
      })
})


const submitTxtForm = () => {
    if (!ruleTxtForm.value) return
    ruleTxtFormRef.value.validate((valid) => {  // 注意：此时使用的是 ruleFormRef.value，而仅写 ruleFormRef 是拿不到值且会报错的;
        if (valid) {
           window.pywebview.api.pyImportLins_data(ruleTxtForm.value.txtlines).then((r) => {
              let mtype = 'success'
              if (r.status=='fail') {
                 mtype='warning'
              }
              if (r.status =='success') {
                 bdList = ref([])
                 jMaterial_getList()
              }
              return ElMessage({
                    message:  '操作成功！',
                    type:mtype,
                  })
           })
        } else {
          console.log('error submit!')
          return false
        }
    })
}

const doModify = ((data)=>{
  for (const i in bdList.value) {
      if (data.id == bdList.value[i].id) {
          bdList.value[i].seourl=data.seourl;
          bdList.value[i].web_name=data.web_name;
          bdList.value[i].seokeyword=data.seokeyword;
          bdList.value[i].isuse=data.isuse;
          bdList.value[i].remark=data.remark;
          window.pywebview.api.pymaterial_updateRec(data).then((r) => {
              if (r.status=='success') {
                  return ElMessage({
                      message: '数据配置保存成功',
                      type: 'success',
                    })
              } else {
                  return ElMessage({
                      message:r.message ,
                      type:'warning',
                    })
              }
          })

      }
  }
})

let tagIds = []
const onSelect = (selection, row) => {
    let selected = selection.length && selection.indexOf(row) !== -1
   // console.log(selected)  // true就是选中，0或者false是取消选中        
    tagIds = []
    for (let i in selection) {
      tagIds.push(selection[i]["id"])
    }
    console.log(tagIds)
}

const handleSelectionChange = (vals) => {
   // let selected = vals.length && vals.indexOf(row) !== -1
   // console.log(selected)  // true就是选中，0或者false是取消选中        
    tagIds = []
    for (let i in vals) {
      tagIds.push(vals[i]["id"])
    }
    console.log(tagIds)
}

const batch_del = () => {
    if (tagIds.length==0) {
       return  ElMessage.warning('请选择要删除的项')
    }
    ElMessageBox.confirm('确定操作吗?')
     .then(() => {
        let tagIdsStr = tagIds.join(",")
        window.pywebview.api.pyDelete_ids(tagIdsStr).then(r=>{
           jMaterial_getList()
           return ElMessage.success(r.message)
        })
      })
}


const statusChangeAll = (()=>{
     if (tagIds.length==0) {
       return  ElMessage.warning('请选择要删除的项')
    }
     ElMessageBox.confirm('确定操作吗?')
     .then(() => {
         let tagIdsStr = tagIds.join(",")
         window.pywebview.api.pyUpdateIsuerAllRec(tagIdsStr).then(r=>{
          jMaterial_getList()
          return ElMessage.success("成功操作!")
       })
     })

})


const clearAll = () => {
  ElMessageBox.confirm('确定全部删除吗?')
     .then(() => {
        let tagIdsStr = tagIds.join(",")
        window.pywebview.api.pyDelete_all_data().then((r) => {
             jMaterial_getList()
             return ElMessage.success(r.message)
          })
      })
}



const jMaterial_getList = (() => {
      window.pywebview.api.material_getList().then((r) => {
        if (r.status == 'fail') {
          // return ElMessage.error(r.message)
            return false;
        }
        if (r.status == 'success') {
          console.log("r.requestdata==",r.requestdata);
          bdList.value = r.requestdata
        }
      })
 
})

const getCurrentTime = () => {
      setInterval(() => {
        let now = new Date();
        // let year = now.getFullYear();
        // let month = now.getMonth() + 1;
        // let day = now.getDate();
        let hour = now.getHours();
        let minute = now.getMinutes();
        let second = now.getSeconds();
        currentTime.value = `${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${second < 10 ? '0' + second : second}`;
      },1000)
}

const bdStart = () => {
   bdstart_status.value = 1
   bdlogRef.value.changeImgLoading(true)
   window.pywebview.api.pybdStart(loop_option.value).then(r=>{
      if (r==1) {
          bdstart_status.value = 0
          bdlogRef.value.changeImgLoading(false)
           ElMessage({
              message: '发包工作结束',
              type: 'success',
              duration:0,
              showClose:true
            })
      }
   })


}

const clearBlogs = () => {
    bdlogRef.value.clearNull()
}

const bdStop = () => {   
  // window.pywebview.api.pyUpdateIsuerAllRec(0).then(r=>{
  //       jMaterial_getList()
  //       bdstart_status.value = 0
  //       return ElMessage.success("批量停止完成!")
  //    })

   bdstart_status.value = 0
}


const pyCallJsTest = () => {
   return ElMessage.success("成功操作!")
}

const clearloggin = () => {
   
   until.clearloggin()
}

const batchChange = (opt) => {
    if (opt=='batch_add') {
        dialogTxtFormVisible.value = true
    }
    if (opt=='batch_status_stop') {
        statusChangeAll()
    }
    if (opt=='batch_del') {
        batch_del()
    }
}

const setconf_handleClose = () => {
     // this.$confirm('确认关闭？')
     //      .then(_ => {
     //        done();
     //      })
     //      .catch(_ => {});
}

 

// const DisclaimerHandleClose = () => {
//   ElMessageBox.confirm('是否同意声明?')
//     .then(() => {
//        disclaimerHandle()
//     })
//     .catch(() => {
//       // catch error
//     })
// }
//
// const disclaimerHandle = () => {
//    //同意
//     dialogDisclaimerVisible.value = false;
//     useStore.setDisclaimer()
//
//     let state = {}
//     state.appcdkey = ''
//     state.disclaimer_agree = true
//
//     window.pywebview.api.pybdSetconfCache('w',state).then((r) => {
//     //console.log(r)
//     })
//
// }


</script>

<style scoped>
:deep(.el-table th.el-table__cell) {
  user-select: text;
}

:deep(.el-table th.el-table__cell .cell) {
  font-weight: normal;
  color: black;
}

:deep(.el-table th.el-table__cell.is-leaf) {
/*  background-color: #ccc;*/
  font-weight:bolder;
  height: 25px;
  padding:0px;
  margin: 0px;
}

:deep(.el-table__body) {
  user-select: text;
  font-size: 0.675rem;
}

:deep(.el-table__body) {
  background-color: #333;
  color: #fff;
   
}

:deep(.el-table tr) {
  background-color: #333;
  color: #fff;
}

:deep(.el-table--border th.el-table__cell) {
    background-color: #333;
    color: #fff;
}

:deep(.el-table th.el-table__cell .cell) {
    font-weight: 550;
    color: #fff;
}
:deep(.el-table-fixed-column--right ) {
    /*background-color: #fff ;*/
}
:deep(.el-table.is-scrolling-none th.el-table-fixed-column--right) {
    background-color: #333;
}

:deep(.el-drawer.rtl.open)   {
    background-color: #333;
}
</style>
